<?php

class GalleryController extends BackOfficeController
{
    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';
    private $_voc;

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id)
    {
        $this->render('view', array(
            'model' => FSM::run('Gallery.PhotoAPI.get', array('id' => $id))->model,
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $this->actionUpdate();
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate()
    {
        //Vocabulary Gallery exists
        $voc = $this->getVocabulary();

        $widgetSetting = array();
        if (Yii::app()->request->IsPostRequest) {
            // save posted data
            $_POST['validateOnly'] = ($this->post('ajax', '') == 'gallery-form');
            $_POST['Term']['v_id'] = $voc->id;
            $result = FSM::run('Gallery.Gallery.save', $_POST);
            $model = $result->model;

            if ($this->post('ajax', '') == 'gallery-form') {
                echo $result->getActiveErrorMessages($result->model);
                Yii::app()->end();
            }
            if (!$result->hasErrors()) {
                $this->message = Yii::t('Core', 'Item has been saved successfully.');
                $this->redirect($this->createUrl('update', array('id' => $model->id)));
            }
        }
        else {
            $model = null;
            $id = $this->get('id', 0);
            //load correct term
            if ($id == 0)
            {
                $model = new Term();
                $model->v_id = $voc->id;
            }
            else
            {
                $model = Term::model()->findByPk($id);    
            }
            if (!is_null($model))
                $model->scenario = 'single_save';
        }

        //load photos
        $photos = array(new Photo());
        if (!is_null($model) && !$model->isNewRecord)
        {
            $criteria = new CDbCriteria();
            $criteria->order = 'ordering ASC';
            $criteria->compare('gallery_id',$model->id);
            $photos = Photo::model()->findAll($criteria);
        }
        if (count($photos) <= 0)
            $photos = array(new Photo());

        $this->render('update', array('model' => $model, 'photos' => $photos));
    }

    protected function getVocabulary()
    {
        if ($this->_voc === null) {
            $voc = Vocabulary::model()->findByAttributes(array('alias' => 'gallery', 'module' => 'Gallery'));
            if (!is_object($voc)) {
                $voc = new Vocabulary;
                $voc->name = 'Gallery';
                $voc->alias = 'gallery';
                $voc->module = 'Gallery';
                if (!$voc->save())
                    Yii::log(CVarDumper::dumpAsString($voc->getErrors()), Clogger::LEVEL_ERROR);
            }
            $this->_voc = $voc;
        }
        return $this->_voc;
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            if (($id = $this->get('id', null)) !== null) {
                $ids = is_numeric($id) ? array($id) : explode(',', $id);
                // delete one or multiple objects given the list of object IDs
                $result = FSM::run('Gallery.Gallery.delete', array('ids' => $ids));
                if ($result->hasErrors()) {
                    echo $result->getError('ErrorCode');
                } elseif (!Yii::app()->request->isAjaxRequest) {
                    // only redirect user to the admin page if it is not an AJAX request
                    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
                }
            } else {
                throw new CHttpException(400, Yii::t('Core', 'Cannot delete item with the given ID.'));
            }
        } else {
            throw new CHttpException(400, Yii::t('Core', 'Invalid request. Please do not repeat this request again.'));
        }
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $this->actionAdmin();
    }

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $model = new Term('search');
        $model->unsetAttributes(); // clear any default values

        $voc = $this->getVocabulary();
        if (is_object($voc))
            $model->v_id = $voc->id;
        if (isset($_GET['Term']))
            $model->attributes = $_GET['Term'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }
}
